package com.barbarossa.vod.utils;

import java.io.File;
import java.net.URI;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.Uri;

import com.barbarossa.vod.datatype.TorrentFile;
import com.barbarossa.vod.datatype.TorrentFileLink;
import com.barbarossa.vod.datatype.VideoLink;
import com.barbarossa.vod.datatype.VodHistoryRecord;

public class VodUtils {

	//http://gdl.lixian.vip.xunlei.com/download?dt=16&g=B44291A274F59E159FDCB2851874D070A3E1DE52&t=2&ui=2&s=476819030&v_type=-1&scn=t5&n=0AE2C640D485560000&p=1&xplaybackid=305fb706-a9a8-11e1-8817-782bcb3dd24d
	
	protected WebUtils webutils;
	
	public VodUtils() {
		webutils = new WebUtils();
		webutils.setReferer("http://vod.xunlei.com/");		
	}
	
	
	public VodHistoryRecord getVodHistoryRecord(String link, boolean asBt) {
		if (asBt) {
			return getVodHistoryRecordFromTorrent(link);
		}
		
		return getVodHistoryRecordFromLink(link);
	}
	
	public VodHistoryRecord getVodHistoryRecordFromTorrent(String torrentFilePathName) {
		VodHistoryRecord ret = new VodHistoryRecord();
		ret.setTorrentRecord(getTorrentRecord(torrentFilePathName, null, null));
		return ret;
	}
	
	public VodHistoryRecord getVodHistoryRecordFromTorrentInfoHash(String filename, String infohash) {
		VodHistoryRecord ret = new VodHistoryRecord();
		ret.setTorrentRecord(getTorrentRecord(null, filename, infohash));
		return ret;
	}

	public VodHistoryRecord getVodHistoryRecordFromLink(String link) {
		VodHistoryRecord ret = new VodHistoryRecord();
		ret.setLinkRecord(getLinkRecord(link, null));
		return ret;
	}

	protected TorrentFile getTorrentRecord(String torrentFilePathName, String torrentFileName, String infohash) {
		TorrentFile ret = new TorrentFile();
		
		ret.setFilePathName(torrentFilePathName);
		ret.setFileName(torrentFileName);
		if (null != infohash)
			ret.setInfoHash(infohash);
		else
			ret.setInfoHash(TorrentUtils.getTorrentHash(torrentFilePathName));
		
		if ((null != ret.getInfoHash())&&(null == torrentFileName)){
			File f = new File(URI.create(torrentFilePathName));
			ret.setFileName(f.getName());
		}
			
		ret.setLinks(getTorrentFileLinksFromTorrentFile(ret));

		return ret;
	}
	
	protected TorrentFileLink[] getTorrentFileLinksFromTorrentFile(TorrentFile torrentFile) {
		TorrentFileLink[] ret = null;
		String infohash = torrentFile.getInfoHash(); 
		if (null == infohash)
			return ret;
		
		String url = "http://i.vod.xunlei.com/req_subBT/info_hash/" + infohash
				+ "/req_num/1000/req_offset/0";

		String html = webutils.getWebpageText(url);
		if (null == html)
			return ret;
		
		try {
			// remove first {}
			html = html.substring(html.indexOf('{') + 1, html.lastIndexOf('}'));
			// remove second {} with {} left
			html = html.substring(html.indexOf('{'), html.lastIndexOf('}') + 1);
			JSONObject json = new JSONObject(html);
			// JSONObject src_info = json.getJSONObject("src_info");
			JSONArray subfile_list = json.getJSONArray("subfile_list");
			
			int indexCount = subfile_list.length();
			ret = new TorrentFileLink[indexCount];
			for (int i = 0; i < indexCount; i++) {
				JSONObject jo = subfile_list.getJSONObject(i);
				ret[i] = new TorrentFileLink();
				ret[i].setTorrent(torrentFile);
				ret[i].setIndex(jo.getInt("index"));
				ret[i].setName(Uri.decode(jo.getString("name")));
				ret[i].setUrl("bt://"+torrentFile.getInfoHash()+"/"+ret[i].getIndex());
				getLinkRecord(ret[i].getUrl(), ret[i]);
			}
			
		} catch (JSONException ex) {
		} catch (Exception ex) {
		}		
		return ret;		
	}
	
	protected VideoLink getLinkRecord(String link, TorrentFileLink torrentFileLink) {
		VideoLink ret = null;
		
		if (null != torrentFileLink)
			ret = torrentFileLink;
		else {
			ret = new VideoLink();
			ret.setUrl(link);
		}
		
		String paramLink = Uri.encode(link);
		String url = "http://i.vod.xunlei.com/req_get_method_vod?url="
				+ paramLink + "&platform=1&userid=2&vip=1&jsonp=downm3u8";
		
		String html = webutils.getWebpageText(url);
		if (null == html)
			return ret;
		
		try {
			//remove downm3u8()			
			html = html.substring(html.indexOf('(') + 1, html.lastIndexOf(')'));
			//remove first {}			
			html = html.substring(html.indexOf('{') + 1, html.lastIndexOf('}'));
			//remove to second {} with {} left			
			html = html.substring(html.indexOf('{'), html.lastIndexOf('}')+1);
			JSONObject json = new JSONObject(html);
			JSONArray vodinfo_list = json.getJSONArray("vodinfo_list");
			JSONObject src_info = json.getJSONObject("src_info");
			String fileName = Uri.decode(src_info.getString("file_name"));
			ret.setName(fileName);
			
			int indexCount = vodinfo_list.length();
			String[] m3u8links = new String[indexCount]; 
			for (int i = 0; i < indexCount; i++) {
				m3u8links[i] = vodinfo_list.getJSONObject(i).getString("vod_url");
			}
			ret.setM3u8Link(m3u8links);
		} catch (JSONException ex) {
		} catch (Exception ex) {
		}		
		
		return ret;
	}
	
}
